What is static and dynamic scope examples?

Static and dynamic scope are two different methods used by programming languages to determine the value of a variable in a program.

Static scope refers to the scope of a variable determined at compile time. The scope of a variable is defined by its position in the source code and is fixed at the time of compilation. In other words, a variable is only accessible within the block in which it is declared or in the blocks nested within it. For example:

var x = 5;
function example() {
    console.log(x);
}
example(); // Output: 5

In this example, the variable "x" is in the global scope and is accessible within the function "example" because it is defined before the function. The output will be 5.

Dynamic scope, on the other hand, refers to the scope of a variable determined at runtime. The scope of a variable is defined by the most recent function call in the call stack. In other words, a variable is accessible from the function where it was declared and all the functions called from it. For example:

function outer() {
    var x = 5;
    function inner() {
        console.log(x);
    }
    inner();
}
outer(); // Output: 5

In this example, the variable "x" is declared within the function "outer" and is accessible within the function "inner" because "inner" is called from "outer". The output will be 5.